package com.inossem.emergency.adapter;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.inossem.emergency.R;
import com.inossem.emergency.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author 王斯宇
 * @time on 2019/7/8 15:06
 * @email siyu.wang@inossem.com
 */
public class BluetoothListAdapter extends RecyclerView.Adapter<BluetoothListAdapter.ViewHolder> {
    private Activity context;
    private List<BluetoothDevice> list = new ArrayList<>();
    private OnItemClickListener listener;

    public BluetoothListAdapter(Activity context) {
        this.context = context;
    }

    public void addDevice(BluetoothDevice device) {
        if(!list.contains(device)) {
            list.add(device);
            notifyDataSetChanged();
        }
    }

    public void clearList() {
        this.list.clear();
        notifyDataSetChanged();
    }
    public void clear() {
        list.clear();
    }

    public void setListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void removeItem(int i) {
        list.remove(i);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_dialog, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        BluetoothDevice device = list.get(i);
        final String deviceName = device.getName();
        if (deviceName != null && deviceName.length() > 0)
            viewHolder.tv.setText(deviceName );
        else
            viewHolder.tv.setText(/*R.string.unknown_device*/device.getAddress());
        viewHolder.layout.setOnClickListener(v -> {
            listener.onItemClick(device.getAddress() , TextUtils.isEmpty(deviceName) ? "" : deviceName);
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public interface OnItemClickListener {
        void onItemClick(String address, String name);

    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.text)
        TextView tv;
        @BindView(R.id.layout)
        RelativeLayout layout;

        public ViewHolder(View itemView) {
            super(itemView);
            Utils.setViewLine(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}
